package com.fvision.camera.utils;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.fvision.camera.manager.DevFileNameManager;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static android.content.Context.ACTIVITY_SERVICE;

/**
 * Created by mayn on 2017/12/13.
 */

public class CameraStateUtil {
    public static int bytesToInt_hight2low(byte[] src, int offset) {
        int value;
        value = (int) ((src[offset] & 0xFF)
                | ((src[offset + 1] & 0xFF) << 8)
                | ((src[offset + 2] & 0xFF) << 16)
                | ((src[offset + 3] & 0xFF) << 24));
        return value;
    }

    public static short bytesToShort(byte[] src, int offset) {
        short value;
        value = (short) ((src[offset] & 0xFF)
                | ((src[offset + 1] & 0xFF) << 8)
        );
        return value;
    }

    /**
     * byte数组转为数字，低位在前，高位在后
     *
     * @param bytes
     * @return
     */
    public static int byte2int_low2hight(byte[] bytes) {
        int length = 0;
        if (bytes.length > 0) {
            length += bytes[0] & 0xff;
        }
        if (bytes.length > 1) {
            length += bytes[1] << 8 & 0xffff;
        }
        if (bytes.length > 2) {
            length += bytes[2] << 16 & 0xffffff;
        }
        if (bytes.length > 3) {
            length += bytes[3] << 24 & 0xffffffff;
        }
        return length;
    }

    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    /**
     * 时间格式转换
     *
     * @return　时长，例：00:00:01
     */
    public static String secondToTimeString(int second) {
        String duration = "";

        int hour = second / 60 / 60;
        int m = second / 60 % 60;
        int s = second % 60;

        //     duration = (hour < 10 ? "0"+hour:hour) + ":";

        duration = duration + (m < 10 ? "0" + m : m) + ":";

        duration = duration + (s < 10 ? "0" + s : s);

        return duration;
    }

    /**
     * Long 转 String
     *
     * @param time   单位秒
     * @param format 格式　如:MM-dd
     * @return 如：3.4
     */
    public static String longToString(long time, String format) {
        if (format == null) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        //前面的lSysTime是秒数，先乘1000得到毫秒数，再转为java.util.Date类型
        Date dt = new Date(time);
        String sDateTime = sdf.format(dt);  //得到精确到秒的表示：08/31/2006 21:08:00
        return sDateTime;
    }

    /**
     * 1 -> 00001 15 -> 00015 150 -> 00150
     *
     * @param num
     * @return
     */
    public static String numFormat(int num) {
        final int length = 5;
        String str = "0000" + num;
        str = str.substring(str.length() - length, str.length());
        return str;
    }

    /**
     * 判断是不是我们的USB记录仪
     *
     * @param usbPath
     * @return
     */
    public static boolean isMyUsb(String usbPath) {
        boolean isn = false;
        File file = new File(usbPath);
        File[] list = file.listFiles();
        if (list == null || list.length < 1 || !file.isDirectory()) {
            return false;
        }
        for (File ff : list) {
            if (ff.getName().equals(DevFileNameManager.getInstance().getCurrentDev().getPreView())) {
                isn = true;
            }
        }
        return isn;
    }

    /**
     * 获取app版本号
     *
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {
        String version = "";
        // 获取packagemanager的实例
        PackageManager packageManager = context.getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo;
        try {
            packInfo = packageManager.getPackageInfo(context.getPackageName(),
                    0);
            version = packInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return version;
    }

    public static String getSDCardCachePath() {
        String path;
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {//
            path = Environment.getExternalStorageDirectory().getPath() + "/";
        } else {
            path = Environment.getDataDirectory().getPath() + "/";
        }
        return path;
    }

    /**
     * 判断服务有没有在运行
     *
     * @return
     */
    public static boolean isServiceRunning(String serivceName, Context context) {
        ActivityManager manager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serivceName.equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取所有存储卡挂载路径
     *
     * @return
     */
    private static List<String> getMountPathList() {
        List<String> pathList = new ArrayList<String>();
        final String cmd = "cat /proc/mounts";
        Runtime run = Runtime.getRuntime();//取得当前JVM的运行时环境
        try {
            Process p = run.exec(cmd);//执行命令
            BufferedInputStream inputStream = new BufferedInputStream(p.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                // 获得命令执行后在控制台的输出信息
                //输出信息内容：  /data/media /storage/emulated/0 sdcardfs rw,nosuid,nodev,relatime,uid=1023,gid=1023 0 0
               // Log.e("getmoutpathlis", line);
                String[] temp = TextUtils.split(line, " ");
                //分析内容可看出第二个空格后面是路径
                String result = temp[1];
                if (result.toLowerCase().contains("udisk") || result.toLowerCase().contains("usb")) {
                    File file = new File(result);
                    //类型为目录、可读、可写，就算是一条挂载路径
                    if (file.isDirectory() && file.canRead() && file.canWrite()) {
                        pathList.add(result);
                    }
                }

                // 检查命令是否执行失败
                if (p.waitFor() != 0 && p.exitValue() == 1) {
                    // p.exitValue()==0表示正常结束，1：非正常结束
//                    Logger.e(命令执行失败!);
                }
            }
            bufferedReader.close();
            inputStream.close();
        } catch (Exception e) {
//            Logger.e(e.toString());
            e.printStackTrace();
            //命令执行异常，就添加默认的路径
            pathList.add("/storage");
        }
        return pathList;
    }

    /**
     * 搜索 strPath目录下，包含searchfile的文件的目录，并且不搜索包含notSearchDir的目录
     *
     * @param strPath
     * @param searchfile
     * @param notSearchDir
     * @return
     */
    private static String searchDir(String strPath, String searchfile, String notSearchDir) {
        if (strPath == null) {
            return null;
        }
        String filename;//文件名
        String suf;//文件后缀
        File dir = new File(strPath);//文件夹dir
        if (!dir.isDirectory()) {
            return null;
        }
        File[] files = dir.listFiles();//文件夹下的所有文件或文件夹

        if (files == null || files.length < 1) {
            return null;
        }

        for (int i = 0; i < files.length; i++) {

            if (files[i].isDirectory()) {
                if (!files[i].getName().contains(notSearchDir)) {
                    searchDir(files[i].getAbsolutePath(), searchfile, notSearchDir);//递归文件夹！！
                }
            } else {
                filename = files[i].getName();
//                int j = filename.lastIndexOf(".");
//                suf = filename.substring(j+1);//得到文件后缀
//                if(suf.equalsIgnoreCase("amr"))//判断是不是msml后缀的文件{
                if (filename.equalsIgnoreCase(searchfile)) {
                    //                   String strFileName = files[i].getAbsolutePath().toLowerCase();
                    return files[i].getAbsolutePath();
                    //                   wechats.add(files[i].getAbsolutePath());//对于文件才把它的路径加到filelist中
                }
            }

        }
        return null;
    }

    /**
     * 判断某个Activity 界面是否在前台
     * @param context
     * @param className 某个界面名称
     * @return
     */
    public static boolean  isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className)) {
            return false;
        }

        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (cpn.getClassName().contains(className)) {
                return true;
            }
        }
        return false;

    }

    /**
     * 判断网络情况
     *
     * @param context 上下文
     * @return false 表示没有网络 true 表示有网络
     */
    public static boolean isNetworkAvalible(Context context) {
        // 获得网络状态管理器
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivityManager == null) {
            return false;
        } else {
            // 建立网络数组
            NetworkInfo[] net_info = connectivityManager.getAllNetworkInfo();

            if (net_info != null) {
                for (int i = 0; i < net_info.length; i++) {
                    // 判断获得的网络状态是否是处于连接状态
                    if (net_info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

}
